/**
 * 维护“客户聊天”时的“自定义侧边栏”
 */
import { Service } from '@gnlab/utils'
import { type OptionalFields } from '@gnlab/utils'
import { MemSubject } from '@gnlab/utils/rx'
import pick from 'lodash/pick'
import type { Services } from '@/services'
import { API } from '@/services/common/api'
import {
  type Sidebar,
  type SystemSidebar,
  type CustomSidebar,
  formatRespSidebars,
  logger,
  systemSidebars,
} from './definition'

export * from './definition'

export class ChatSidebars extends Service<Services> {
  private get auth() {
    return this.services.auth
  }

  list = new MemSubject<Sidebar[]>([])

  registered() {
    void Promise.resolve(this.auth.accountId).then(() => void this.load())
  }

  async load() {
    const res = await API('/Config/GetSidebars', { formatter: formatRespSidebars })
    if (res.success) {
      this.list.next(res.data)
    } else {
      logger.warn('聊天侧边栏加载失败', res.error)
      this.list.next(systemSidebars)
    }
  }

  async addOrUpdate(
    sidebar: OptionalFields<SystemSidebar, 'id'> | OptionalFields<Omit<CustomSidebar, 'key'>, 'id'>,
  ) {
    const data = sidebar.system
      ? {
          id: sidebar.id,
          name: `system-${sidebar.key}-${Date.now()}`,
          url: JSON.stringify({ system: true, key: sidebar.key, disabled: sidebar.disabled }),
        }
      : {
          id: sidebar.id,
          name: sidebar.name,
          url: JSON.stringify(pick(sidebar, 'system', 'scope', 'disabled', 'url')),
        }
    const res = await API('/Config/SaveSidebar', { data })
    void this.load()
    if (!res.success) logger.warn(`聊天侧边栏保存失败：${res.error}`)
    return res
  }

  async remove(id: number) {
    const res = await API('/Config/RemoveSidebar', { data: { Id: id } })
    void this.load()
    if (!res.success) logger.warn(`聊天侧边栏删除失败：${res.error}`)
    return res
  }
}
